package com.rpc.rpcservercontainer;

import com.rpc.rpcservercontainer.PackageReader.RpcPackage;
import com.rpc.rpcserverdef.RpcServer;
import com.rpc.rpcserverdef.RpcServerException;
import java.util.Properties;
import org.apache.log4j.Logger;


/**
 *Wrapper around RPC server apps to be contained within a new thread.
 */
public class RpcPackageRunner implements Runnable {
    private static final Logger log = Logger.getLogger(RpcPackageRunner.class);
    
    private final PackageReader.RpcPackage pckge;

    RpcPackageRunner(RpcPackage pckge) {
        this.pckge = pckge;
    }
    
    
    /**
     *Starts RPC Server application.
     */
    public void run() 
    {
        final Properties appConfig = pckge.getConfig();
        
        
        final String serverType = (String) appConfig.getProperty("ServerType");
        
        if (log.isDebugEnabled())
        {
            log.debug("App: " + pckge.getName() + " configured for server type: " + serverType + "; Searching for RpcServer implementation.");
        }
        
        final RpcServer rpcServer = RpcServers.getRpcServerByName(serverType);
        
        if (rpcServer == null) 
        {
            log.error("Could not find RpcServer for '" + serverType + "'; App: " + pckge.getName() + " will not be started.");
            return;
        }
        
        
        try 
        {
            if (log.isDebugEnabled()) {
                log.debug("Calling to RpcServer.start for app '" + pckge.getName() +"'");
            }
            
            rpcServer.start(appConfig);
            
            if (log.isDebugEnabled()) {
                log.debug("RpcServer.start called sucessfully for app '" + pckge.getName() +"'");
            }
            
        } catch (RpcServerException ex) {
            log.error("Unable to start app '" + pckge.getName() + "'", ex);
 
            throw new RuntimeException("Unable to start app '" + pckge.getName() + "'", ex);
        }
    }
    
}
